package dfs_bfs.test79;

/**
 * 单词搜索
 * @author code_yc
 * @version 1.0
 * @date 2020/7/9 9:19
 */
public class Solution2 {

    // dfs去标记数组的解法
    int m, n;
    char[][] _board;
    String _word;

    public boolean exist(char[][] board, String word) {
        m = board.length;
        n = board[0].length;
        _board = board;
        _word = word;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(i, j, 0)) return true;
            }
        }
        return false;
    }

    private boolean dfs(int i, int j, int c) {
        if (_board[i][j] != _word.charAt(c)) return false;
        if (c == _word.length() - 1) return true;
        int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
        _board[i][j] = '.';
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && y >= 0 && x < m && y < n) {
                if (dfs(x, y, c + 1)) return true;
            }
        }
        _board[i][j] = _word.charAt(c);
        return false;
    }
}
